import asyncio
import os
import threading
import time

import uvicorn
from fastapi import FastAPI, Depends

from contextlib import asynccontextmanager

from apps.app_utils import make_api_offline, app_init
from configs.base_config import configs
from configs.log_config import LOGGING_CONFIG

app = FastAPI()

app_init(app)
make_api_offline(app)

reload_excludes = ["data"]  # 不从加载目录


@app.get("/")
async def root() -> dict:
    pid = os.getpid()
    print("当前进程的进程号（PID）是:", pid)
    tid = threading.get_ident()
    print("当前线程的线程号（TID）是:", tid)
    return {"message": "Hello World"}


@app.get("/hello/{name}")
async def say_hello(name: str):
    pid = os.getpid()
    print("当前进程的进程号（PID）是:", pid)
    tid = threading.get_ident()
    print("当前线程的线程号（TID）是:", tid)
    time.sleep(10)
    return {"message": f"Hello {name}"}


@asynccontextmanager
async def get_lock():
    lock = asyncio.Lock()
    await lock.acquire()
    try:
        yield lock
    finally:
        lock.release()


count = 0


@app.get("/api")
async def api_endpoint(lock: asyncio.Lock = Depends(get_lock)):
    # 执行需要互斥操作的代码块
    global count
    print(id(lock))
    count += 1
    return count


if __name__ == "__main__":
    uvicorn.run("main:app", host="0.0.0.0", port=configs.PORT, reload=True, # log_config=LOGGING_CONFIG,
                reload_excludes=reload_excludes, workers=4)
